import {
	Component
} from 'react';
import {
	Tab,
	Button,
	ScrollList,
	Datetime,
	Group,
	Boxs,
	Avatar,
	Badge,
	Popup,
	ActionSheet,
	Dialog,
	Toast,
	SearchBar
} from 'saltui';
const {
	IconButton,
	ButtonGroup
} = Button;
const {
	HBox,
	Box,
	VBox
} = Boxs;

import PageController from 'pages/home';
import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap
} from '../../../app/variables';
import DB from '../../../app/db';
import PostPageItem from 'components/post_page_item';

const Item1 = React.createClass({
	render: function() {
		return (
			<div>
				<p>{this.props.id}</p>
			</div>
		);
	}
});
let tabPage = '0';
export default class PageHome extends Component {
	constructor(props) {
		super(props);
		tabPage = '0';
		var hasBottomTab =  document.getElementById("hasBottomTab").value;
		let winHeight = hasBottomTab == 1 ? getScrollHigh(1, 1, 1) : getScrollHigh(1, 1, 0);
		this.state = {
			winHeight: winHeight,
			activeTabIndex:tabPage,
			search: {
				title:'',
				startDate:'',
				endDate:''
			},
			visible:false,
			typeArrow:true,
			isConfirm:false,
			addClickAble:true,
			noDataTip:"暂无数据"
		}
		/**
		 * 办理页面搜索框设置项
		 * @type {{locale: string, instantSearch: boolean, hasHistory: boolean, searchDelay: number, onEnter: (()), onExit: (()), onChange: ((p1:*)), onSearch: ((p1?:*))}}
		 */
		this.searchBarProps = {
			placeholder: "搜贴,找人,搜版块",
			instantSearch: false,
			hasHistory: false,
			searchDelay: 450,
			exitAfterEnter: false,
			onEnter: () => {
			},
			onExit: this.onExit.bind(this),
			onChange: (value) => {
			},
			onSearch: this.onSearch.bind(this)
		};

	}

	componentDidMount() {
		//获取首页信息
		let t = this;
		t.searchBarLimit('30');
		this.flushData({}, tabPage);
		this.dislodgeActionSheet();
		Dialog.hide();
	}

	searchBarLimit(len){
		$(".t-search-bar-input").attr('maxlength',len);
	}

	//返回时关闭已打开的ActionSheet
	dislodgeActionSheet(){
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if(isAndroid==true){
           document.addEventListener('backbutton', function(e) {
            $('.t-popup-mask').trigger('click');
            e.preventDefault();
           });
      }else if(isiOS==true){
          dd.biz.navigation.setLeft({
              control: true,//是否控制点击事件，true 控制，false 不控制， 默认false
              text: '',//控制显示文本，空字符串表示显示默认文本
              onSuccess : function(result) {
                $('.t-popup-mask').trigger('click');
                $('.t-popup-mask').trigger('click');
                backPage();
              },
              onFail : function(err) {}
          });
      }
    }

	/**
	 * tab页切换方法
	 * @param obj
	 */
	handleTabChange(obj) {
		var t = this;
		var active = obj.active;
		tabPage = obj.active;
		this.setState({
			activeTabIndex: active,
			search: {
				title:'',
				startDate:'',
				endDate:''
			},
		});
		this.flushData({}, active);
		//搜索字数限制
		t.searchBarLimit('30');
	}

	/**
	 * 点击新增按钮跳转到新增页面
	 */
	addButtonClick() {
		location.href = '#/post/edit';
	}

	beforeFetch(data, from) {
	//	Object.assign(data, from);
		this.setState({
			addClickAble:false,
		});
		data.activeTabIndex = this.state.activeTabIndex;
		data.rows = data.pageSize;
		//data.start = (data.page - 1) * data.pageSize;
		data.limit = data.pageSize;
		data.title=this.state.search.title;
		if(this.state.search.startDate != null && this.state.search.startDate != ''){
			data.startDate = this.formatterDate(this.state.search.startDate);
		}
		if(this.state.search.endDate != null && this.state.search.endDate != ''){
			data.endDate = this.formatterDate(this.state.search.endDate);
		}
		//data.type="0";//不以公告置顶排序
		data.type="1";//以公告置顶排序
		return data;
	}

	processData(data) {
		this.setState({
			addClickAble:true,
		});
		// data.currentPage = data.currentPage + 1;
		return data;
	}

	onExit() {
		this.setState({
			noDataTip:"无搜索结果"
		});
		this.onSearch("");
	}

	onSearch(value) {
		this.setState({
			noDataTip:"无搜索结果"
		});
		let param = this.state.search;
		param.title=value;
		param.startDate=this.state.search.startDate;
		param.endDate=this.state.search.endDate;
    	this.flushData(param,tabPage);
	}

	changeArrow(field){
	    let t = this;
	    let status = t.state[field];
	    t.setState({
	      [field]:!status
	    })
	}

	onRefresh(value) {
		let param = this.state.search;
		param.title=value;
		param.startDate=this.state.search.startDate;
		param.endDate=this.state.search.endDate;
    	this.flushData(param,tabPage);
	}

	flushData(param, index) {
		let swap_index = index ? index : this.state.activeTabIndex;
		if (swap_index == '0') {
			dd.biz.navigation.setTitle({
      		title: '最新',
		    onSuccess: function (result) {},
     		onFail: function () {}
    		});
			this.flushNewData(param);
		} else if (swap_index == '1') {
			dd.biz.navigation.setTitle({
      		title: '最热',
		    onSuccess: function (result) {},
     		onFail: function () {}
    		});
			this.flushHotData(param);
		}
	}

	changeClickAble(){
		this.setState({
			addClickAble:true,
		});
	}

	flushNewData(param) {
		this.refs.post_new_ref.fetchData(param);
	}

	flushHotData(param) {
		this.refs.post_hot_ref.fetchData(param);
	}
	
	//日期选择器开关
	showSlot(id) {
		this[id].show();
	}

	//时间格式化   YYYY-MM-DD
	formatterDate(time){
		var date = new Date(time);
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate();
		return Y+M+D;
	}

	refresh(){
		let param = this.state.search;
		param.title=this.state.search.title;
		param.startDate=this.state.search.startDate;
		param.endDate=this.state.search.endDate;
    	this.flushData(param,tabPage);
	}

	//日期选择确认
	onOk(value,key){
		let t = this;
		if(key == "startDate" && t.state.search.endDate != null && t.state.search.endDate != ''){
		  if(t.formatterDate(t.state.search.endDate) < t.formatterDate(value.value)){
			Toast.show({
			  type: 'error',
			  content: '开始日期不能大于结束日期'
			});
			return;
		  }
		}
		if(key == "endDate" && t.state.search.startDate != null && t.state.search.startDate != ''){
		  if(t.formatterDate(t.state.search.startDate) > t.formatterDate(value.value)){
			Toast.show({
			  type: 'error',
			  content: '结束日期不能小于开始日期'
			});
			return;
		  }
		}
		if(key == "startDate"){
			var title = t.state.search.title;
			var endDate = t.state.search.endDate;
			t.setState({
				search :{
					title:title,
					startDate:t.formatterDate(value.value),
					endDate:endDate
				}
			});
		}else{
			var title = t.state.search.title;
			var startDate = t.state.search.startDate;
			t.setState({
				search :{
					title:title,
					startDate:startDate,
					endDate:t.formatterDate(value.value),
				}
			});
		}
	}
	

	render() {
		let winHeightStyle = {
			height:this.state.winHeight
		};
		const datetimeProps = {
			locale: 'zh-cn',
		};
		return (
			<div className="t-PB44">
				<Tab activeKey={this.state.activeTabIndex} onChange={this.handleTabChange.bind(this)} destroyInactiveTabPane={true}>
				 	<Tab.Item key="0" title={"最新"}>
					<VBox className="dd-bottom-border">
						<HBox className="t-BCf" vAlign="center">
							<Box flex={1}><SearchBar ref="search_post_new_ref" {...this.searchBarProps} /></Box>
							<Box className="t-FCddblue" onClick={() => { 
								this.setState({ visible: true });
								var top = $(window).scrollTop();
								$('#App').css("top",-top+"px");
								$('#App').css("width",100+"%");
								$('#App').css('position','fixed');
								}}>
								<i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"></i>
							</Box>
						</HBox>
					</VBox>
					<div style={winHeightStyle} >
						<ScrollList
						url={URLS.queryPostPageWithNew}
						dataType="json"
						pageSize={10}
						ref="post_new_ref"
						beforeFetch={this.beforeFetch.bind(this)}
						processData={this.processData.bind(this)}
						onRefresh={this.onRefresh.bind(this)}
						noDataImage={nodataIcon}
						noDataTip={this.state.noDataTip}
						currentPageKey="page"
						fetchDataOnOpen={false}
						>
						<PostPageItem pagetype="all" addClickAble={this.state.addClickAble} changeClickAble={this.changeClickAble.bind(this)} 
						    isShowLabel={true} isShowCount={true} flushData={this.flushNewData.bind(this)} />
                        </ScrollList>
                    </div>
                    </Tab.Item>
					<Tab.Item key="1" title={"最热"}>
					<VBox className="dd-bottom-border">
						<HBox className="t-BCf" vAlign="center">
							<Box flex={1}><SearchBar ref="search_post_hot_ref" {...this.searchBarProps} /></Box>
							<Box className="t-FCddblue" onClick={() => { 
								this.setState({ visible: true });
								var top = $(window).scrollTop();
								$('#App').css("top",-top+"px");
								$('#App').css("width",100+"%");
								$('#App').css('position','fixed');
								}}>
								<i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"></i>
							</Box>
						</HBox>
					</VBox>
                    <div style={winHeightStyle}>
						<ScrollList
						url={URLS.queryPostPageWithHot}
						dataType="json"
						pageSize={10}
						ref="post_hot_ref"
						beforeFetch={this.beforeFetch.bind(this)}
						processData={this.processData.bind(this)}
						onRefresh={this.onRefresh.bind(this)}
						noDataImage={nodataIcon}
						noDataTip={this.state.noDataTip}
						currentPageKey="page"
						fetchDataOnOpen={false}
						>
						<PostPageItem pagetype="all" addClickAble={this.state.addClickAble} changeClickAble={this.changeClickAble.bind(this)} 
						    isShowLabel={true} isShowCount={true} activeValue={this.state.activeTabIndex} flushData={this.flushHotData.bind(this)} />
		    			</ScrollList>
                    </div>
                    </Tab.Item>
				</Tab>
				<Popup
					content={
						<div style={{height:'100vh'}}>
						<div className="dd-popup-mail-right" style={{width:"280px",paddingTop:0,height:"calc(100% - 80px)",overflowY:"auto"}}>
						    <HBox vAlign="center"
								className={!this.state.typeArrow?"t-P16 t-PT14 t-PB0 t-FS16 t-MT4":"dd-bottom-border t-P16 t-PT14 t-PB0 t-FS16 t-MT4"}
								onClick={this.changeArrow.bind(this,"typeArrow")}>
								<Box flex={1} className="t-FC3">发布日期</Box>
								<Box><i className={this.state.typeArrow?"iconfont icon-arrow-down t-FCddblue":"iconfont icon-arrow-up t-FCddblue"} ></i></Box>
							</HBox>
							<HBox vAlign="center" className={!this.state.typeArrow?"t-PL16":"t-DN"}>
								<Box className="t-FC9 t-FS14">开始日期</Box>
								<Box className="t-BCf7 t-LH32 t-R4 t-ML5" onClick={() => {this.showSlot('slot1');}} style={{width:'70%',marginLeft:'16px'}}>
									<p className="t-FAC t-H26">{this.state.search.startDate} <i className="iconfont icon-calendar t-FS14 t-FCblue t-FR t-MR10"></i></p>
									<Datetime
									{...datetimeProps}
									slotRef={s => this.slot1 = s}
									title="日期选择"
									placeholder="开始日期"
									value={this.state.search.startDate}
									columns={Datetime.YMD}
									onConfirm={(value) => {this.onOk(value, 'startDate'); }}
									onCancel={() => {  }}
									/>
								</Box>
							</HBox>
							<div className="t-H10"></div>
							<HBox vAlign="center" className={!this.state.typeArrow?"t-PL16":"t-DN"}>
                                <Box className="t-FC9 t-FS14">结束日期</Box>
                                <Box className="t-BCf7 t-LH32 t-R4 t-ML5" onClick={() => {this.showSlot('slot2');}} style={{width:'70%',marginLeft:'16px'}}>
                                <p className="t-FAC t-H26">{this.state.search.endDate}<i className="iconfont icon-calendar t-FS14  t-FCblue t-FR t-MR10"></i></p>
								<Datetime
								{...datetimeProps}
								slotRef={s => this.slot2 = s}
								title="日期选择"
								placeholder="结束日期"
								value={this.state.search.endDate}
								columns={Datetime.YMD}
								onConfirm={(value) => { this.onOk(value, 'endDate'); }}
								onCancel={() => {  }}
								/>
							</Box>
							</HBox>
							<div className="t-bottom-fixed"  style={{borderTop:0,bottom:'0',width:'100%'}}>
							<ButtonGroup onClick={() => { Popup.hide(); }}>
								<Button type="secondary" display="inline" onClick={() => { this.setState({search:{startDate:'',endDate:'',title:this.state.search.title},noDataTip:'暂无数据'}, ()=>{ this.refresh() }) }}>重置</Button>
								<Button type="primary" display="inline" onClick={() => {this.setState({visible: false,noDataTip:'无搜索结果'}); this.refresh() }}>确定</Button>
							</ButtonGroup>
							</div>
						</div>
						</div>
					}
					animationType="slide-left"
					onMaskClick={() => { this.setState({ visible : false }); }}
				    visible={this.state.visible}
					>
					{null}
				</Popup>
				<IconButton className="add-new-page t-BCddblue" onClick={this.addButtonClick.bind(this)}><i className="iconfont icon-plus t-FCf"></i></IconButton>
                <PageController activeIndex={0}/>
		   </div>
		);
	}
}